from plugin import plugin
import plugins
import psycopg2

__doc__ = "database"

class database(plugin):
	"Database interface to enable persistent plugins"
	
	def __init__(self):
		self._version = '3.0 testing'
		self._conn = psycopg2.connect("dbname=changeme user=changeme password=changeme")
		
	def __del__(self):
		try:
			self._conn.commit()
			self._conn.close()
		except: pass
	
	@property
	def _execute(self):
		"Note! not really safe! May throw errors if database connection isnt live"
		cur = self._conn.cursor()
		return cur.execute
	
	def _exec(self, func, data=[]):
		cur = self._conn.cursor()

		try:
			if len(data) > 0:
				cur.execute(func, data)
			else:
				cur.execute(func)
		except:
			return None

		self._conn.commit()
		try:
			res = cur.fetchall()
			cur.close()
			return res
		except:
			cur.close()
			return [('No results!', '')]

	def _report(self, msg, result):
		self._irc.reply(msg, ', '.join([';'.join(r) for r in result]))

	@plugins.irc_throw
	def db(self, msg, args):
		"Allows admins to perform psql functions"
		if not msg['sender']['admin']:
			return 'Error! You must be an admin!'
		if hasattr(self, '_' + args) and callable(getattr(self, '_' + args)):
			return getattr(self, '_' + args)()
		return 'Result: ' + ', '.join([';'.join(x) for x in self._exec(args)])
	
	def _install(self):
		self._exec("CREATE TABLE config(key varchar(255), value varchar(255));")
		self._exec("CREATE TABLE admins(name varchar(255));")
		self._exec("CREATE TABLE plugins(name varchar(255), enabled BOOL);")
		self._exec("CREATE TABLE todo(nick varchar(255), item varchar(1024));")
		self._exec("CREATE TABLE mailbox(to_nick varchar(255), from_nick varchar(255), msg varchar(1024));")
		self._exec("CREATE TABLE reminders(nick varchar(255), dates DATE, list varchar(1024));")
		self._exec("CREATE TABLE stats(nick varchar(255), data varchar(4096));")
		self._exec("CREATE TABLE dominos(code varchar(255));")
		self._update()
	
	def _update(self):
		self._exec("DELETE FROM config *;")
		self._exec("INSERT INTO config VALUES('nick', %s);", (self._irc.nick, ))
		self._exec("DELETE FROM admins *;")
		for admin in self._irc.admins:
			self._exec("INSERT INTO admins VALUES(%s);", (admin,))
		self._exec("DELETE FROM plugins *;")
		for module in self._mods:
			self._exec("INSERT INTO plugins VALUES(%s, TRUE);", (module,))
	
	def _uninstall(self):
		self._exec("DROP TABLE config;")
		self._exec("DROP TABLE admins;")
		self._exec("DROP TABLE plugins;")
		self._exec("DROP TABLE todo;")
		self._exec("DROP TABLE mailbox;")
		self._exec("DROP TABLE reminders;")
		self._exec("DROP TABLE stats;")
		self._exec("DROP TABLE dominos;")
		
